/**
 * 
 */
package com.googlecode.bestpaper;

import java.io.File;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.googlecode.bestpaper.BestpaperParser.book_return;
import com.googlecode.bestpaper.output.pdf.book.PDFBook;
import com.googlecode.bestpaper.utils.BestpaperUtils;

/**
 * @author xalinx at gmail dot com
 * @date Dec 28, 2009
 */
public class Bestpaper {
	void buildPDF(String wiki, File pdf) throws Exception {
		PDFBook book = eval(wiki);
		book.build(pdf, 0);
	}

	private PDFBook eval(String bp) throws RecognitionException {
		CharStream input = new ANTLRStringStream(bp);
		BestpaperLexer lexer = new BestpaperLexer(input);
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		BestpaperParser parser = new BestpaperParser(tokens);
		book_return r = parser.book();
		CommonTree t = (CommonTree) r.getTree();
		CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
		BestpaperEval walker = new BestpaperEval(nodes);
		return walker.book();
	}

	private static final String INPUT = "-input=";
	private static final String OUTPUT = "-output=";
	private static final String FORMAT = "-format=";
	private static final String FORMAT_PDF = "pdf";
	private static final String ENCODING = "-encoding=";
	private static final String ENCODING_UTF8 = "utf-8";

	public static void main(String[] args) throws Exception {
		String input = null;
		String output = null;
		String format = FORMAT_PDF;
		String encoding = ENCODING_UTF8;
		Bestpaper bp = new Bestpaper();
		for (String item : args) {
			if (item.startsWith(INPUT)) {
				input = item.substring(INPUT.length());
			} else if (item.startsWith(OUTPUT)) {
				output = item.substring(OUTPUT.length());
			} else if (item.startsWith(FORMAT)) {
				format = item.substring(FORMAT.length());
			} else if (item.startsWith(ENCODING)) {
				encoding = item.substring(ENCODING.length());
			}
		}
		if (input == null) {
			throw new IllegalArgumentException("Must specify -input=xxx");
		}
		File inputFile = new File(input);
		File inputParentFile = inputFile.getParentFile();
		if (null != inputParentFile) {
			BestpaperUtils.setInputFileDirPath(inputParentFile.getAbsolutePath());
		}
		File outputFile = null;
		if (output == null) {
			String filename = StringUtils.split(inputFile.getName(), '.')[0];
			outputFile = new File(inputParentFile, filename + "." + FORMAT_PDF);
		} else {
			outputFile = new File(output);
		}

		if (FORMAT_PDF.equals(format)) {
			String content = FileUtils.readFileToString(inputFile, encoding);
			bp.buildPDF(content, outputFile);
		}
	}
}
